#include "threadPool.h"
#include <limits.h>
void send_train001(int netfd, char buf[], int len){
    train_t train;
    memset(&train, 0, sizeof(train));
    train.length = len;
    memcpy(train.data, buf, train.length);
    printf("now_send train.data = %s\n", train.data);
    send(netfd, &train, sizeof(int)+train.length, MSG_NOSIGNAL);
}
int get_pre_id(cmdInfo_t *pcmdinfo, MYSQL *mysql){
    printf("pcmdinfo->filaName = %s\n", pcmdinfo->fileName);
    char sql[4096] = {0};
    int pre_id = 0;
    char pathbuf_for_select[100] = {0};
    strcpy(pathbuf_for_select, pcmdinfo->cmdPath);
    pathbuf_for_select[strlen(pathbuf_for_select) - 1] = '\0';//去除当前路径pcmdinfo->cmdPath最右边的'/'
    memset(&sql, 0, 4096);
    sprintf(sql, "select file_id from virtualFile where path_client = '%s' and user_id = %d;", pathbuf_for_select, pcmdinfo->user_id);
    int qret = mysql_query(mysql, sql);
    //if(qret != 0){
    //    fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
    //    printf("puts 第 2 个 mysql_query failed!\n");
    //    return -2;
    //}
    MYSQL_RES * result = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(result);
    if(row == NULL){
        pre_id = -1;
    }else{
        pre_id = atoi(row[0]);
    }
    return pre_id;
    printf("第一次检查，pre_id = %d\n", pre_id);
}

//服务端本来是没有所谓上传的，但是为了响应客户端的puts操作
int PUTS_Server(int netfd, cmdInfo_t *pcmdinfo, MYSQL *mysql){
    printf("\n");
    printf("fileName = %s\n", pcmdinfo->fileName);
    printf("cmdPath = %s\n", pcmdinfo->cmdPath);
    char p[100] = {0};
    strcpy(p, pcmdinfo->cmdPath);
    strcat(p, pcmdinfo->fileName);
    strcpy(pcmdinfo->arg, p);
    printf("path_client = %s\n", pcmdinfo->cmdPath);
    //在进入这个接口函数之前，服务端已经接收客户端发过来的命令结构，里面保存着关于命令信息的一切
    //第 001 步，根据传过来的cmdInfo_t *pcmdinfo命令结构体，进行查表
    //发现有和该文件哈希值一样的文件哈希值，直接实现秒传！
    char sql[4096] = {0};
    sprintf(sql, "select file_hash from virtualFile where file_hash = '%s';", pcmdinfo->md5);
    int qret = mysql_query(mysql, sql);
    if(qret != 0){
        fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
        printf("puts 第 1 个 mysql_query failed!\n");
        char buf005[] = "no!";
        send_train001(netfd, buf005, sizeof(buf005));
        return -1;
    }
    printf("mysql_query执行完成！\n");
    MYSQL_RES * result = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(result);
    //printf("row[0] = %s\n", row[0]);
    printf("已经取表和取行！\n");
    printf("--------------001\n");
    //这里能进入，表示实现了秒传
    if(row != NULL){
        printf("-------------002\n");
        int pre_id = get_pre_id(pcmdinfo, mysql);
        if(pre_id == -2){
            char buf006[] = "no!";
            send_train001(netfd, buf006, sizeof(buf006));
            return -1;
        }
        else{
            printf("第二次确认，pre_id = %d\n", pre_id);
        }
        //再查表，解决上传重复文件名的情况
        memset(sql, 0, sizeof(sql));
        sprintf(sql, "select file_name from virtualFile where file_name = '%s'", pcmdinfo->fileName);
        int qret001 = mysql_query(mysql, sql);
        if(qret001 != 0){
            fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
            printf("puts 不知道第几个 mysql failed!\n");
            char buf10086[] = "no!";
            send_train001(netfd, buf10086, sizeof(buf10086));
            return -1;
        }
        printf("mysql_query 执行完成！\n");
        MYSQL_RES * result = mysql_store_result(mysql);
        MYSQL_ROW row = mysql_fetch_row(result);
        if(row != NULL){//这里不为空，表示查到这个数据了
            char buf10010[] = "warning!";
            send_train001(netfd, buf10010, sizeof(buf10010));
            return -1;
        }

        //走到这里，表示已经得到pre_id，至此虚拟文件表所有元素全部集齐，起飞！
        //小步骤 003，将该文件插入到虚拟文件表中
        memset(sql, 0, sizeof(sql));
        if(pcmdinfo->fileSize > INT_MAX || pcmdinfo->fileSize < INT_MIN){
            fprintf(stderr, "Error: file_size exceeds the range of INT.\n");
            char buf003[] = "no!";
            send_train001(netfd, buf003, sizeof(buf003));
            return -1;
        }else{
            sprintf(sql, "insert into virtualFile (file_name,user_id,pre_id,path_client,file_size,file_type,file_hash,curr_path)"
                    " values ('%s',%d,%d,'%s',%d,'c','%s','%s');",
                    pcmdinfo->fileName,
                    pcmdinfo->user_id,
                    pre_id,
                    pcmdinfo->arg,
                    (int)pcmdinfo->fileSize,
                    pcmdinfo->md5,
                    pcmdinfo->cmdPath);
            qret = mysql_query(mysql, sql);
            if(qret != 0){
                fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
                printf("puts 第 3 个 mysql_query failed!\n");
                char buf004[] = "no!";
                send_train001(netfd, buf004, sizeof(buf004));
                return -1;
            }
            printf("插入成功，实现秒传！\n");
            //创建个临时变量，发送过去，告诉客户端，实现了秒传
            char buf[] = "ok";
            send_train001(netfd, buf, sizeof(buf));
        }
        mysql_free_result(result);//记得关闭连接，emmm，感觉mysql_close更直接
        printf("mysql得到的result已经释放！\n");
        return 0;
    }
    //不是秒传，也要发一个信息过去，告诉客户端
    printf("-------进入正常接收逻辑！\n");

    //再查表，解决上传重复文件名的情况
    memset(sql, 0, sizeof(sql));
    sprintf(sql, "select file_name from virtualFile where file_name = '%s'", pcmdinfo->fileName);
    int qret001 = mysql_query(mysql, sql);
    if(qret001 != 0){
        fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
        printf("puts 不知道第几个 mysql failed!\n");
        char buf10086[] = "no!";
        send_train001(netfd, buf10086, sizeof(buf10086));
        return -1;
    }
    printf("mysql_query 执行完成！\n");
    MYSQL_RES * result001 = mysql_store_result(mysql);
    MYSQL_ROW row001 = mysql_fetch_row(result);
    if(row001 != NULL){//这里不为空，表示查到这个数据了
        char buf10010[] = "warning!";
        send_train001(netfd, buf10010, sizeof(buf10010));
        return -1;
    }

    //走到这里，表示正常传输，同时也要发送一个yes告诉客户端
    char buf4321[] = "sdlkd";
    send_train001(netfd, buf4321, sizeof(buf4321));

    //这里不搞else了，一旦文件哈希值不一样，直接接收客户端上传的文件
    printf("未能秒传！\n");
    int ret = recvFile(netfd, pcmdinfo);
    printf("recvFile ret = %d\n", ret);

    char buf123456[] = "ojbk!";
    send_train001(netfd, buf123456, sizeof(buf123456));
    printf("走到这里，表示接收成功！\n");
    //接收完成之后，插入虚拟文件表
    int pre_id = get_pre_id(pcmdinfo, mysql);
    printf("第二次确认，pre_id = %d\n", pre_id);

    //走到这里，表示已经得到pre_id，至此虚拟文件表所有元素全部集齐，起飞！
    //小步骤 003，将该文件插入到虚拟文件表中
    memset(sql, 0, sizeof(sql));
    sprintf(sql, "insert into virtualFile (file_name,user_id,pre_id,path_client,file_size,file_type,file_hash,curr_path)"
            " values ('%s',%d,%d,'%s',%d,'c','%s','%s');",
            pcmdinfo->fileName,
            pcmdinfo->user_id,
            pre_id,
            pcmdinfo->arg,
            (int)pcmdinfo->fileSize,
            pcmdinfo->md5,
            pcmdinfo->cmdPath);
    printf("sql = %s\n", sql);
    qret = mysql_query(mysql, sql);
    if(qret != 0){
        fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
        printf("puts 第 3 个 mysql_query failed!\n");
        char buf004[] = "no!";
        send_train001(netfd, buf004, sizeof(buf004));
        return -1;
    }
    //char buf123[] = "ojbk!";
    //send_train001(netfd, buf123, sizeof(buf123));
    //printf("服务端发送 ojbk!\n");
    return 0;
}

int GETS_Server(int netfd, cmdInfo_t *pcmdinfo, MYSQL *mysql){
    //前面已经收过cmdInfo_t *数据到 pcmdinfo里面了
    //先判断 arg 是不是有效文件路径名
    //char *p;
    //char duplicate[100] = {0};
    //strcpy(duplicate, pcmdinfo->arg);
    //p = strtok(duplicate," /");
    //char *lastToken = NULL;
    //while(p != NULL){
    //    lastToken = p;
    //    p = strtok(NULL, "/");
    //}
    //if(lastToken != NULL){
    //    memcpy(pcmdinfo->fileName, lastToken, strlen(lastToken)+1);
    //    printf("选择下载的文件是 %s\n", pcmdinfo->fileName);
    //}else{
    //    pcmdinfo->fileName[0] = '\0';
    //    printf("请选定具体文件！\n");
    //    return -1;
    //}
    //printf("pcmdinfo->fileSize = %ld\n", pcmdinfo->fileSize);
    //printf("pcmdinfo->fileName = %s\n", pcmdinfo->fileName);

    char sql[4096] = {0};
    sprintf(sql, "select file_name from virtualFile where file_name = '%s' and path_client = '%s';", pcmdinfo->fileName, pcmdinfo->arg);
    MYSQL_RES *result = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(result);
    if(row == NULL){
        //走到这里，表示没找到文件，返回没有该文件
        char buf9999[] = "-1";
        send_train001(netfd, buf9999, sizeof(buf9999));
        printf("该文件不存在！\n");
        return -1;
    }
    else{//表示找到同名同路径的文件
        memset(sql, 0, sizeof(sql));
        sprintf(sql, "select * from virtualFile where file_name = '%s' and path_client = '%s';", pcmdinfo->fileName, pcmdinfo->arg);
        MYSQL_RES *result001 = mysql_store_result(mysql);
        MYSQL_ROW row001 = mysql_fetch_row(result);
        if(strcmp(row[6], "d") == 0){
            //表示找到的文件是 目录类型，返回-1
            char buf10000[] = "-2";
            send_train001(netfd, buf10000, sizeof(buf10000));
            printf("客户端要下载目录，pass！\n");
            return -1;
        }
        else if(strcmp(row[6], "c") == 0){
            //表示找到的文件确实是正经文件，速速开始下载
            char buf10001[] = "0";
            send_train001(netfd, buf10001, sizeof(buf10001));
            printf("准备下载！\n");
            //继续往下走
        }
    }
    int ret = sendFile(netfd, pcmdinfo);
    if(ret == -1){
        printf("Gets发送文件给客户端失败！\n");
        return -1;
    }
    return 0;
}
